package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.properties.JwtProperties;
import com.hmdp.service.IUserService;
import com.hmdp.utils.JwtUtil;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.JwtClaimsConstant.JWT_KEY;
import static com.hmdp.utils.JwtClaimsConstant.USER_ID;
import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 发送验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }

        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //将验证码存入Redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //发送验证码
        log.info("验证码发送成功{}", code);
        return Result.ok();
    }

    /**
     * 用户登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    // @TODO 2.使用JWT实现登录功能
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        // 3.从redis获取验证码并校验
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();

        // @TODO 假如要生成1k个用户测试的话，注释掉以下部分，先不校验验证码
        if(cacheCode == null || !cacheCode.equals(code)){
            //3.不一致，报错
            return Result.fail("验证码错误");
        }

        //一致，根据手机号查询用户
        User user = query().eq("phone", phone).one();

        //5.判断用户是否存在
        if (user == null) {
            //不存在，则创建
            user = createUserWithPhone(phone);
        }

        // 6.生成JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put(USER_ID, user.getId());
//        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(),jwtProperties.getTtl(),claims);
//        String jwtToken = JwtUtil.createJWT("ThisIsA32BytesLongSecretKeyForHS256",30*60*1000,claims);
        String jwtToken = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);


        // 7.保存用户信息到 redis中
        // 7.1.随机生成token，作为登录令牌
//        String token = UUID.randomUUID().toString(true);
        // 7.2.将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //beanToMap方法执行了对象到Map的转换
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        //BeanUtil在转换过程中忽略所有null值的属性
                        .setIgnoreNullValue(true)
                        //对于每个字段值，它简单地调用toString()方法，将字段值转换为字符串。
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        // 7.3.存储
        String tokenKey = LOGIN_USER_KEY + userDTO.getId();
        // 7.4.将jwtToken存入userMap中
        userMap.put(JWT_KEY, jwtToken);
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        // 7.5.设置redis中 userId的有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 本地ThreadLocal也存一份
        UserHolder.saveUser(userDTO);
        // 8.返回token
        return Result.ok(jwtToken);
    }

    /**
     * 签到功能
     *
     * @return
     */
    @Override
    public Result sign() {
        //获取当前用户id
        UserDTO user = UserHolder.getUser();
        if (Objects.isNull(user)) {
            return Result.fail("当前未登录");
        }
        //拼接key
        Long userId = user.getId();
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = DateTimeFormatter.ofPattern(":yyyyMM").format(now);
        String key = USER_SIGN_KEY + userId + keySuffix;
        //存入bitmap
        stringRedisTemplate.opsForValue().setBit(key, now.getDayOfMonth() - 1, true);
        return Result.ok();
    }

    /**
     * 统计连续签到天数
     *
     * @return
     */
    @Override
    public Result signCount() {
        //获取当前用户id
        UserDTO user = UserHolder.getUser();
        if (Objects.isNull(user)) {
            return Result.fail("当前未登录");
        }
        //拼接key
        Long userId = user.getId();
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = DateTimeFormatter.ofPattern(":yyyyMM").format(now);
        String key = USER_SIGN_KEY + userId + keySuffix;
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        // 5.获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202203 GET u14 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            //没有任何签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        int count = 0;
        while ((num & 1) != 0) {
            count++;
            num >>>= 1;
        }
        return Result.ok(count);
    }

    /**
     * 提出登录
     * @return Result
     */
    @Override
    public Result logout() {
        Long userId = UserHolder.getUser().getId();
        //组装拼接key
        String tokenKey = LOGIN_USER_KEY + userId;
        //从redis中删除用户的key
        stringRedisTemplate.delete(tokenKey);
        //从UserHolder中删除当前用户
        UserHolder.removeUser();
        return Result.ok("已退出登录");
    }

    /**
     * 根据手机号创建用户并保存
     *
     * @param phone
     * @return User
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        //2.保存用户
        this.save(user);
        return user;
    }

}